import { login, getUserInfo, getUserDetail } from '@/api/user'

import { resetRouter } from '@/router'
const state = {
  // token密钥
  token: localStorage.getItem('HR_TOKEN') || '',
  // 用户信息
  userInfo: null
}
const mutations = {
  // 将获取的数据值赋值到 token中
  setToken(state, data) {
    state.token = data
    localStorage.setItem('HR_TOKEN', data)
  },
  //   将获取用户的信息赋值到 userInfo中
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeToken(state) {
    state.token = ''
    localStorage.setItem('HR_TOKEN', '')
  },
  removeUserInfo(state) {
    state.userInfo = null
  }
}
const actions = {
  // 登录
  async handleLogin(state, data) {
    const RES = await login(data)
    state.commit('setToken', RES)
    localStorage.setItem('stampTimes', +Date.now())
  },
  // 获取用户信息
  async getUserInfo(state) {
    // 用户基本信息
    const RES = await getUserInfo()
    // 用户详细信息
    const DETAIL = await getUserDetail(RES.userId)
    state.commit('setUserInfo', { ...RES, ...DETAIL })
  },
  logout(state) {
    state.commit('removeToken')
    state.commit('removeUserInfo')
    resetRouter()
  }
}

export default {
  // 命名空间锁
  namespaced: true,
  state,
  mutations,
  actions
}

